package com.elite.groovy.davco.clink;

import com.elite.groovy.util.Util;
import com.tinet.clink.core.auth.Credentials;
import com.tinet.clink.core.auth.SignatureComposer;
import com.tinet.clink.core.auth.Signer;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.utils.URIBuilder;

import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @projectName: Degao_Clink
 * @package: com.elite.groovy.davco.clink
 * @className: SignUtil
 * @description: TODO
 * @author: LiJT
 * @date: 2023-10-27 11:13
 * @version: 1.0
 */
public class ClinkUtils {
    private static final Log log = LogFactory.getLog(ClinkUtils.class);
    private static String accessKeyId = "ea4478dba2ca33fc67fe0b1f43df5430";
    private static String accessKeySecret = "5T5q9u1cNSB2234Gio8L";
    private static String apiURI = "api-sh.clink.cn";

    private static Map<String, String> queryParameters = new HashMap<String, String>();
    private static SignatureComposer composer = new SignatureComposer();
    private static Signer signer = Signer.getSigner();

    public static void main(String[] args) throws Exception {


        /*String StartTime = "1667232000";
        String EndTime = "1667318400";
        log.debug("doCallBack Data StartTime:" + StartTime + " EndTime:" + EndTime);

        int Offset = 0;

        // 封装调用头Heads
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");

        // 系统接入-GET
        String getPath = "/cc/list_cdr_ibs?";

        Map<String, String> queryParams = new HashMap<String, String>();
        queryParams.put("startTime", String.valueOf(StartTime));
        queryParams.put("endTime", String.valueOf(EndTime));
        queryParams.put("offset", String.valueOf(Offset));
        queryParams.put("limit", "10");
        String doGETRes = ClinkUtils.doClinkCall("GET", getPath, queryParams, headMap, null);
        // log.debug("系统接入 doGETRes:" + doGETRes);

        JSONObject doGETJSON = JSONObject.fromObject(doGETRes);
        log.debug("1-呼入通话记录 Data Result:" + doGETJSON);*/

        /*String StartTime = "20221202";
        log.debug("doCallBack Data StartTime:" + StartTime);

        // 封装调用头Heads
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");

        // 系统接入-GET
        String getPath = "/cc/copy_cdr_ib_details?";

        String Offset = "";

        Map<String, String> queryParams = new HashMap<String, String>();

        queryParams.put("date", StartTime);
        if (!KHUtil.isNull(Offset)) {
            queryParams.put("scrollId", Offset);
        }
        String doGETRes = ClinkUtils.doClinkCall("GET", getPath, queryParams, headMap, null);
        // log.debug("系统接入 doGETRes:" + doGETRes);

        JSONObject doGETJSON = JSONObject.fromObject(doGETRes);
        log.debug("1-呼入通话记录 Data Result:" + doGETJSON);*/

        /*// 封装调用头Heads
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");

        // 系统接入-GET
        String getPath = "/cc/list_queues?";

        String Offset = "";

        Map<String, String> queryParams = new HashMap<String, String>();

        if (!KHUtil.isNull(Offset)) {
            queryParams.put("scrollId", Offset);
        }
        String doGETRes = ClinkUtils.doClinkCall("GET", getPath, queryParams, headMap, null);
        // log.debug("系统接入 doGETRes:" + doGETRes);

        JSONObject doGETJSON = JSONObject.fromObject(doGETRes);
        log.debug("1-队列列表 Data Result:" + doGETJSON);*/


        // 封装调用头Heads
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");

        // 系统接入-GET
        String getPath = "/cc/describe_queue?";

        Map<String, String> queryParams = new HashMap<String, String>();

        queryParams.put("qno", "0528");

        String doGETRes = ClinkUtils.doClinkCall("GET", getPath, queryParams, headMap, null);
        // log.debug("系统接入 doGETRes:" + doGETRes);

        JSONObject doGETJSON = JSONObject.fromObject(doGETRes);
        log.debug("1-队列列表 Data Result:" + doGETJSON);

    }

    // 调用天润Main
    public static String doClinkCall(String httpMethod, String apiPath, Map<String, String> queryParams, Map<String, String> mapHeaders, JSONObject sendJSON) throws Exception {

        // 系统接入
        log.debug("doClinkCall Params httpMethod:" + httpMethod + " URI:" + apiURI + " queryParams:" + queryParams + " PostJSON:" + sendJSON);
        queryParameters.clear();

        // 请求头合并
        if (queryParams.size() > 0) {
            for (String key : queryParams.keySet()) {
                putQueryParameter(key, queryParams.get(key));
            }
            log.debug("doClinkCall queryParameters:" + queryParameters);
        }

        // 公共参数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        putQueryParameter("AccessKeyId", accessKeyId);
        putQueryParameter("Expires", 3600);
        putQueryParameter("Timestamp", sdf.format(new Date()));
        String stringToSign = composer.getStringToSign(httpMethod, apiURI, apiPath, queryParameters);
        String signature = signer.signString(stringToSign, new Credentials(accessKeyId, accessKeySecret));
        putQueryParameter("Signature", signature);

        String doCallURL = "https://" + apiURI + apiPath + generateUri();
        log.debug("doClinkCall URL:" + doCallURL);

        String doCallRes = "";
        if (httpMethod.equals("POST")) {
            doCallRes = Util.doHttpPostUseHead(doCallURL, sendJSON.toString(), "UTF-8", 10000, 0, mapHeaders);
        } else {

            doCallRes = Util.doHttpGetUseHead(doCallURL, "UTF-8", 10000, 0, mapHeaders);
        }
        // log.debug("doClinkCall Result:" + doCallRes);

        return doCallRes;
    }

    // 生成URI
    public static String generateUri() throws URISyntaxException {
        URIBuilder builder = new URIBuilder();
        for (String key : queryParameters.keySet()) {
            builder.setParameter(key, queryParameters.get(key));
        }
        return builder.build().getQuery();
    }

    // 处理参数
    protected static void putQueryParameter(String name, Object value) {
        try {
            String encodedKey = URLEncoder.encode(name, "UTF-8");
            String encodedValue = URLEncoder.encode(String.valueOf(value), "UTF-8");
            queryParameters.put(encodedKey, encodedValue);
        } catch (Exception e) {
            queryParameters.put(name, String.valueOf(value));
            log.warn("调用天润Clink Exception", e);
        }
    }

    static String stampToDate(String s) {
        String res = s.length() > 10 ? s : s + "000";
        System.out.println("res:" + res);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        long lt = new Long(res);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    // 调用天润支持GET || POST
    public static String doClinkCall2(String httpMethod, String apiPath, Map<String, String> queryParams, Map<String, String> mapHeaders, JSONObject sendJSON) throws Exception {

        // 系统接入
        log.debug("doClinkCall Params httpMethod:" + httpMethod + " URI:" + apiURI + " queryParams:" + queryParams + " PostJSON:" + sendJSON);

        // 基础初始化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        queryParameters.clear();

        // 公共参数
        putQueryParameter("AccessKeyId", accessKeyId);
        putQueryParameter("Expires", 3600);
        putQueryParameter("Timestamp", sdf.format(new Date()));

        // 如果Get 请求头合并
        if (httpMethod.toUpperCase().equals("GET")) {
            for (String key : queryParams.keySet()) {
                putQueryParameter(key, queryParams.get(key));
            }

        }

        // 获取公用签名信息
        String stringToSign = composer.getStringToSign(httpMethod, apiURI, apiPath, queryParameters);
        String signature = signer.signString(stringToSign, new Credentials(accessKeyId, accessKeySecret));
        putQueryParameter("Signature", URLEncoder.encode(signature));

        // 获取调用URL
        String doCallURL = "https://" + apiURI + apiPath + generateUri();
        log.debug("doClinkCall URL:" + doCallURL);

        String doCallRes = "";
        if (httpMethod.equals("POST")) {
            doCallRes = Util.doHttpPostUseHead(doCallURL, queryParams.size() > 0 ? generateUriPOST(queryParams) : sendJSON.toString(), "UTF-8", 10000, 0, mapHeaders);

        } else {
            doCallRes = Util.doHttpGetUseHead(doCallURL, "UTF-8", 10000, 0, mapHeaders);

        }
        // log.debug("doClinkCall Result:" + doCallRes);

        return doCallRes;
    }

    // 生成URI
    public static String generateUriPOST(Map<String, String> queryParamsURL) throws URISyntaxException {
        URIBuilder builder = new URIBuilder();
        for (String key : queryParamsURL.keySet()) {
            builder.setParameter(key, queryParamsURL.get(key));
        }
        return builder.build().getQuery();
    }
}
